<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <h1>sessionStorage</h1>
  <button id="save">save</button>
  <button id="get">get</button>
  <button id="remove">remove</button>
  <button id="clear">clear</button>

  <script>
    const btn = document.getElementById('save');
    btn.addEventListener('click', () => {
      const obj = {
        name: 'John',
        age: 30,
        sex: 'male',
        city: 'New York'
      }
      // for (let i = 0; i < 100000; i++) {
      //   sessionStorage.setItem(`user${i}`, JSON.stringify(obj));
      // }

      // 当有存储超出限制时会报错，catch用来捕获错误
      try {
        sessionStorage.setItem('user', JSON.stringify(obj)); // 转成JSON字符串会让对象按原样保留
      } catch (error) {
        if (error instanceof DOMException && error.name === 'QuotaExceededError') {
          console.log('超出限制');
          // 清除所有的sessionStorage（一般是这个方法） || 清除最早的sessionStorage（LRU算法）
          sessionStorage.clear();
          sessionStorage.setItem('user', JSON.stringify(obj));
        }
        console.log(error);
      }

      // localStorage.setItem('user', obj); //这样会变成普通字符串
      // sessionStorage.setItem('user', JSON.stringify(obj)); // 转成JSON字符串会让对象按原样保留
    });

    const btn2 = document.getElementById('get');
    btn2.addEventListener('click', () => {
      const user = sessionStorage.getItem('user');// 读取本地存储的某条数据
      // console.log(user);
      console.log(JSON.parse(user));
    });

    const btn3 = document.getElementById('remove');
    btn3.addEventListener('click', () => {
      sessionStorage.removeItem('user');// 删除本地存储的某条数据
    });

    const btn4 = document.getElementById('clear');
    btn4.addEventListener('click', () => {
      sessionStorage.clear();// 清空本地存储的所有数据
    });
  </script>
</body>
</html>